import 'dart:io';

import 'package:super_study_language_tools/tools/tools_common.dart';

import '../model/model_srt_span.dart';

class ToolsSubtitle {
  static const int SRT_MIN_INTERVAL = 50;

  // static List<String> symbols = [" ", ",", ".", "!", "?", "'", "\""];
  static List<String> symbols = [" ", ",", ".", "!", "?", "\"", "...", "-", ":"];

  // 处理所有字幕
  static List<String> handleAll(String str) {
    List<String> arr1 = str.split(" ");
    List<String> arr2 = [];
    for (int i = 0; i < arr1.length; i++) {
      if (i != 0) {
        arr2.add(" ");
      }
      if (arr1[i].length > 0) {
        arr2.add(arr1[i]);
      }
    }

    for (int i = 0; i < symbols.length; i++) {
      String s = symbols[i];

      arr1 = arr2;
      arr2 = [];

      for (int i = 0; i < arr1.length; i++) {
        String str = arr1[i];
        if (str.length > 1 && str.indexOf(s) > -1) {
          List<String> arr3 = str.split(s);
          for (int j = 0; j < arr3.length; j++) {
            if (j != 0) {
              arr2.add(s);
            }
            if (arr3[j].length > 0) {
              arr2.add(arr3[j]);
            }
          }
        } else {
          arr2.add(str);
        }
      }
    }
    return arr2;
  }

  // 将一行字幕转换为单词列表
  // Hello world,zhangsan !
  // =>
  // hello world zhangsan
  static List<String> strToWords(String str) {
    // 使用空格分隔
    List<String> arr1 = str.split(" ");
    List<String> arr2 = [];
    for (int i = 0; i < arr1.length; i++) {
      if (arr1[i].length > 0) {
        arr2.add(arr1[i].toLowerCase());
      }
    }

    // 使用其他符号分割
    for (int i = 0; i < symbols.length; i++) {
      String s = symbols[i];
      arr1 = arr2;
      arr2 = [];
      for (int i = 0; i < arr1.length; i++) {
        String str = arr1[i];
        if (str.length < 1) continue;
        if (str.indexOf(s) > -1) {
          List<String> arr3 = str.split(s);
          for (int j = 0; j < arr3.length; j++) {
            if (arr3[j].length > 0) {
              arr2.add(arr3[j]);
            }
          }
        } else {
          arr2.add(str);
        }
      }
    }
    return arr2;
  }

  // 将字幕文本转换为字幕对象数组
  static List<ModelSrtSpan> handleSrtContent(String content) {
    var result = <ModelSrtSpan>[];
    var lines = <String>[];
    content = content.replaceAll("\r\n", "\n");
    lines = content.split("\n");
    print("总行数:${lines.length}");

    for (int i = 0; i < lines.length; i++) {
      String line1 = lines[i];
      if (line1.length < 1) {
        // print("空行跳过");
        continue;
      }

      if (isNumeric(line1)) {
        // 时间间隔
        i++;
        String line2 = lines[i];
        if (line2.indexOf("-->") != -1) {
          var times = line2.split("-->");
          if (times.length == 2) {
            String startTime = times[0].trim();
            String endTime = times[1].trim();

            i++;
            String line3 = lines[i];
            // print("编号:" + line1);
            // print("开始时间:" + startTime);
            // print("结束时间:" + endTime);
            // print("字幕内容:" + line3);

            String nextLine = "";
            do {
              i++;
              if (i >= lines.length) break;
              nextLine = lines[i];
              if (nextLine.length > 0) {
                line3 += " " + nextLine;
              }
            } while (nextLine.length > 0);

            line3 = line3.replaceAll("<i>", "");
            line3 = line3.replaceAll("</i>", "");

            int tmp1 = line3.indexOf("(");
            int tmp2 = line3.indexOf(")");
            if (tmp1 != -1 && tmp2 != -1) {
              String a = line3.substring(0, tmp1);
              String b = line3.substring(tmp2 + 1);
              line3 = a + b;
            }

            int tmp3 = line3.indexOf(":");
            if (tmp3 != -1) {
              line3 = line3.substring(tmp3 + 1);
            }

            if (line3.length > 0) {
              ModelSrtSpan srt =
                  ModelSrtSpan(int.parse(line1), toMicroSecond(startTime), toMicroSecond(endTime), line3);
              result.add(srt);
            }
            // srt.id = int.parse(line1);
            // srt.startTime = toMicroSecond(startTime);
            // srt.endTime = toMicroSecond(endTime);
            // srt.content = line3;
          } else {
            print("没有-->");
          }
        } else {
          print("数字后面不是时间间隔,不处理");
        }
      }
    }
    return result;
  }

  // 判断是否为数字
  static bool isNumeric(String str) {
    return int.tryParse(str) != null;
  }

  // 字符串转换为时间毫秒
  static int toMicroSecond(String str) {
    // 00:21:15,707
    var tmp1 = str.split(",");
    var tmp2 = tmp1[0]; // 00:21:15
    var tmp3 = tmp1[1]; // 707
    var tmp4 = tmp2.split(":"); // 00 21 15
    var result = ((int.parse(tmp4[0]) * 60 + int.parse(tmp4[1])) * 60 + int.parse(tmp4[2])) * 1000 + int.parse(tmp3);
    return result;
  }

  static String toHHmms(int t) {
    int h = t ~/ 1000 ~/ 60 ~/ 60;
    int m = t ~/ 1000 ~/ 60 % 60;
    int s = t ~/ 1000 % 60;
    int sss = t % 1000;
    String HH = h.toString();
    String MM = m.toString();
    String SS = s.toString();
    String SSS = sss.toString();
    if (HH.length < 2) {
      HH = "0$HH";
    }
    if (MM.length < 2) {
      MM = "0$MM";
    }
    if (SS.length < 2) {
      SS = "0$SS";
    }
    if (SSS.length < 3) {
      SSS = "0$SSS";
    }
    if (SSS.length < 3) {
      SSS = "0$SSS";
    }
    return "$HH:$MM:$SS";
  }

  static String toHHmmss(int t) {
    int h = t ~/ 1000 ~/ 60 ~/ 60;
    int m = t ~/ 1000 ~/ 60 % 60;
    int s = t ~/ 1000 % 60;
    int sss = t % 1000;
    String HH = h.toString();
    String MM = m.toString();
    String SS = s.toString();
    String SSS = sss.toString();
    if (HH.length < 2) {
      HH = "0$HH";
    }
    if (MM.length < 2) {
      MM = "0$MM";
    }
    if (SS.length < 2) {
      SS = "0$SS";
    }
    if (SSS.length < 3) {
      SSS = "0$SSS";
    }
    if (SSS.length < 3) {
      SSS = "0$SSS";
    }
    return "$HH:$MM:$SS,$SSS";
  }

  // 检查输入是否匹配
  static List<bool> check(List<String> subtitleWords, List<String> inputWords) {
    List<bool> checkList = [];
    List<bool> used = [];

    for (int i = 0; i < inputWords!.length; i++) {
      used.add(false);
    }

    for (int j = 0; j < subtitleWords!.length; j++) {
      if (symbols.contains(subtitleWords![j])) {
        checkList.add(true);
      } else {
        checkList.add(false);
        for (int i = 0; i < inputWords!.length; i++) {
          if (used[i] == false && subtitleWords![j].toLowerCase() == inputWords![i].toLowerCase()) {
            checkList[j] = true;
            used[i] = true;
            break;
          }
        }
      }
    }
    return checkList;
  }

  // 分析字幕星系
  static List analysisSrtContent(content) {
    int sentenceQty = 0;
    int wordQty = 0;

    int speed = 0;

    int wordAllQty = 0;
    int allTime = 0;

    List<ModelSrtSpan> list = handleSrtContent(content);

    sentenceQty = list.length;

    Set wordSet = new Set();
    for (int i = 0; i < list.length; i++) {
      ModelSrtSpan s = list[i];
      List<String> words = strToWords(s.content);
      wordSet.addAll(words);
      wordAllQty += words.length;
      allTime += s.endTime - s.startTime;
    }
    wordQty = wordSet.length;
    speed = wordAllQty * 60 * 1000 ~/ allTime;

    return [sentenceQty, wordQty, speed, wordSet];
  }

  static void saveSrts(List<ModelSrtSpan> _srts,String _srtPath1) {
    String str = "";
    for (int i = 0; i < _srts.length; i++) {
      ModelSrtSpan srt = _srts[i];
      // str += srt.id.toString();
      str += (i + 1).toString();
      str += "\r\n";
      str += ToolsSubtitle.toHHmmss(srt.startTime);
      str += " --> ";
      str += ToolsSubtitle.toHHmmss(srt.endTime);
      str += "\r\n";
      str += _srts[i].content;
      str += "\r\n";
      str += "\r\n";
    }
    print(str);
    print(_srtPath1!);
    File file1 = File(_srtPath1!);
    // file1.rename(_srtPath1! + "_bak" + getNowTimeStr());
    file1.renameSync(_srtPath1! + "_bak" + ToolsCommon.getNowTimeStr());

    File file = File(_srtPath1!);
    file.writeAsString(str);
  }
}
